package com.shaoyuwang;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 动态SQL，防止被SQL注入
 */
public class DynamicSQLDemo {
    public static void main(String[] args) throws SQLException {

        MysqlDataSource db = new MysqlDataSource();
        db.setServerName("localhost");
        db.setPort(3306);
        db.setUser("root");
        db.setPassword("123456");
        db.setDatabaseName("lib_0403");
        db.setUseSSL(false);
        db.setCharacterEncoding("utf-8");
        db.setServerTimezone("Asia/Shanghai");

        Scanner scanner = new Scanner(System.in);
        String n = scanner.nextLine();
        try (Connection c = db.getConnection()) {
//            //被 SQL 注入
//            String sql = "select reid, rid, bid, borrowed_at from records where reid > " + n + " order by reid";
            // ? 表示占位符
            String sql = "select reid, rid, bid, borrowed_at from records where reid > ? order by reid";

            try (PreparedStatement ps = c.prepareStatement(sql)) {
                // 有了 PreparedStatment 之后
                // execute 之前
                // 为占位符绑定真实的数据
                // 1表示第i个?，n表示填入的数据
                ps.setString(1, n);
                System.out.println(ps);

                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        int reid = rs.getInt(1);
                        int rid = rs.getInt("rid");
                        String bid = rs.getString(3);
                        String borrowedAt = rs.getString("borrowed_at");

                        System.out.printf("%d, %d, %s, %s\n", reid, rid, bid, borrowedAt);
                    }
                }
            }
        }
    }
}
